import React, { Component } from "react";
import { NavBar, Icon, SearchBar } from "antd-mobile";
import "./SearchCenter.scss";
import myaxios from "../../utils/myaxios";
import { withRouter } from "react-router-dom"
class SearchCenter extends Component {
  state = {
    inputVal: '',
    productList: []
  }
  // 获取数据
  getProductList = (params) => {
    // 如果为空
    if (this.state.inputVal){
      myaxios.get('goods/qsearch', {
        params: {
          query: this.state.inputVal
        }
      })
        .then(res => {
          if (res.length){
            this.setState({
              productList: res
            })
          }else{
            alert('暂无此类商品')
          }
        })
    }else{
      alert('输入不能为空')
    }
  }
  // 根据点击跳转页面
  handleItemClick = (e) => {
    let good_id = e.target.getAttribute('data-goods_id')
    this.props.history.push('/goodDetail/' + good_id)
  }
  render() {
    return (
      <div className="yg-sc">
        <NavBar
          className="yg-sc-nav"
          mode="light"
          icon={<Icon type="left" />}
          onLeftClick={() => window.history.go(-1)}
        >
          搜索中心
        </NavBar>
        {/* 搜索中心输入框开始 */}
        <SearchBar
          focus
          className="yg-sc-search"
          placeholder="Search"
          value={this.state.inputVal}
          // 是键盘 按下 enter 键触发
          onSubmit={() => this.getProductList()}
          // 清除输入内容时触发的
          // onClear={(value) => console.log(value, "onClear")}
          // 聚焦的时候 触发
          // onFocus={() => console.log("onFocus")}
          // 失焦 触发
          // onBlur={() => console.log("onBlur")}
          //点击图标
          onCancel={() => this.getProductList()}
          // showCancelButton
          cancelText="搜索"
          // 内容改变的时候触发
          onChange={(value) => {
              this.setState({
                inputVal: value,
              });
          }}
        />
        {/* 搜索中心输入框结束 */}
        {/* 产品列表开始 */}
        <div className="yg-sc-list" onClick={this.handleItemClick}>
          {this.state.productList.map(v => {
            return (
              <div className="sc-list-item" key={v.goods_id} data-goods_id={v.goods_id}>
                {v.goods_name}
              </div>
            )
          })}
        </div>
        {/* 产品列表结束 */}
      </div>
    );
  }
}

export default withRouter(SearchCenter)
